package com.bindapp.http;

import android.util.Log;

import com.bindapp.listener.HttpListener;
import com.bindapp.util.GsonUtil;
import com.bindapp.util.Static;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;

import static android.R.attr.data;

/**
 * Created by apple on 2018/6/27.
 */

public class MNetSocketHttp {
    public static MNetSocketHttp mNetHttp;

    public DatagramSocket mSocket;
    private ReceiveThread mReceiveThread;
    private SendThread mSendThread;
    private ConnectThread mConnectThread;
    private Thread timer;
    //private List<String> messageQueue;
    private String sendStr;
    private Class<?> clazz;
    private HttpListener listener;
    //private TimeCount timeCount;


    /*private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1){
                case 1:
                    clearThread();
                    listener.success(msg.obj);
                    break;
                case 2:
                    listener.fail("网络异常");
                    clearThread();
                    break;
            }


        }
    };*/

    public static MNetSocketHttp getInstance() {
        if (mNetHttp == null) {
            mNetHttp=new MNetSocketHttp();
        }
        return mNetHttp;
    }


    public void getNormalRequest(Map<String,Object> map, Class<?> clazz,HttpListener listener){
        connect();
        this.clazz = clazz;
        this.listener = listener;
        String content = GsonUtil.getInstance().getJson(map);//"{'op':'login','password':'1','userId':'test'}";

        mSendThread = new SendThread(content);
        mSendThread.start();
    }



    public void connect(){
        try {
            if(mSocket == null||mSocket.isClosed()){
                mSocket=new DatagramSocket();

            }
            if(mConnectThread==null){
                mConnectThread=new ConnectThread();
            }
            //mConnectThread=null;
            //mConnectThread.interrupt();
            mConnectThread.start();


            timer=new Thread(new TimerRuner());
            mReceiveThread = new ReceiveThread();
            //timeCount=new TimeCount(3000, 1000,new TimeCountImpl());
            mReceiveThread.start();
            timer.start();


        } catch (SocketException e) {
            e.printStackTrace();
            clearThread();
        }
    }


    private void clearThread(){
        if(timer!=null){
            timer.interrupt();
            timer=null;
        }
        if(mReceiveThread!=null){
            mReceiveThread.interrupt();
            mReceiveThread=null;
        }
        if(mSendThread!=null){
            mSendThread.interrupt();
            mSendThread=null;
        }
        if(mConnectThread!=null){
            mConnectThread.interrupt();
            mConnectThread=null;
        }
    }

    private class TimerRuner implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(3*1000);
                listener.fail("网络异常");
                clearThread();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private class ConnectThread extends Thread{

        @Override
        public void run() {
            super.run();
            try {
                mSocket.connect(InetAddress.getByName(Static.IPServer),Static.PORT);
                Static.myLog("连接结束");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    }

    private class ReceiveThread extends Thread {
        @ Override
        public void run() {
            super.run();
            if (mSocket == null || mSocket.isClosed())
                return;
            try {
                //timeCount.start();
                byte datas[] = new byte[1024];
                DatagramPacket packet = new DatagramPacket(datas, datas.length, InetAddress.getByName(Static.IPServer), Static.PORT);
                mSocket.receive(packet);
                String receiveMsg = new String(packet.getData()).trim();
                Log.e("Mytext", "receive--->" + receiveMsg);

                clearThread();
                listener.success(GsonUtil.getInstance().getObject(receiveMsg,clazz));
//GsonUtil.getInstance().getObject(receiveMsg,clazz)

                /*Message msg=new Message();
                msg.arg1 = 1;
                msg.obj = GsonUtil.getInstance().getObject(receiveMsg,clazz);
                mHandler.sendMessage(msg);*/
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class SendThread extends Thread {
        private String sendmsg;
        public SendThread(String sendmsg){
            this.sendmsg=sendmsg;
        }
        @ Override
        public void run() {
            super.run();
            try {
                if (mSocket == null || mSocket.isClosed())
                    return;

                byte[]datas = sendmsg.getBytes();
                InetAddress address = InetAddress.getByName(Static.IPServer);
                final DatagramPacket packet = new DatagramPacket(datas, datas.length, address, Static.PORT);
                mSocket.send(packet);
                Log.e("Mytext", "send--->" + data);
                //messageQueue.remove(0);
                if(mSendThread!=null){
                    mSendThread.interrupt();
                    mSendThread=null;
                }

            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*class TimeCountImpl implements TimeCountListener{

        @Override
        public void onTick(long millisUntilFinished) {
            Static.myLog("onTick-->"+millisUntilFinished);

        }

        @Override
        public void onFinish() {
            *//*Message msg=new Message();
            msg.arg1=2;
            mHandler.sendMessage(msg);*//*

            listener.fail("网络异常");
            clearThread();

        }
    }*/


}
